import 'dart:convert';
import 'dart:developer';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:custom_refresh_indicator/custom_refresh_indicator.dart';
import 'package:flutter/material.dart';
import 'package:insta_image_viewer/insta_image_viewer.dart';
import 'package:school_assistant/common_colors.dart';
import 'package:school_assistant/shiwu_add_page.dart';
import 'package:school_assistant/toast_utils.dart';
import 'package:school_assistant/user_feedback_imgs.dart';

import 'package:get/get.dart';
import 'data/goods_moni.dart';
import 'data/shiwu_entity.dart';

class ShiwuPage extends StatefulWidget {
  const ShiwuPage({Key? key}) : super(key: key);

  @override
  State<ShiwuPage> createState() => _ShiwuPageState();
}

class _ShiwuPageState extends State<ShiwuPage> {
  List<ShiwuEntity> shiwu = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: CommonColor.colorF5,
        body: CustomRefreshIndicator(
          child: ListView.builder(
            itemBuilder: (cxt, index) => _getItem(index),
            itemCount: 1 + shiwu.length,
          ),
          builder: MaterialIndicatorDelegate(
            builder: (context, controller) {
              return Icon(
                Icons.ac_unit,
                color: Colors.blue,
                size: 30,
              );
            },
          ),
          onRefresh: myAsyncRefreshFunction,
        ));
  }

  _getItem(int index) {
    if (index == 0) {
      return Row(
        children: [
          Expanded(
            child: GestureDetector(
              child: Container(
                margin:
                    EdgeInsets.only(top: 12, left: 12, right: 6, bottom: 12),
                padding:
                    EdgeInsets.only(top: 15, left: 10, right: 15, bottom: 15),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(10)),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.search,
                      size: 30,
                      color: CommonColor.colorMainGreen,
                    ),
                    SizedBox(
                      width: 12,
                    ),
                    Column(
                      children: [
                        Text("寻物启事"),
                        SizedBox(
                          height: 6,
                        ),
                        Container(
                          padding:
                              EdgeInsets.symmetric(vertical: 4, horizontal: 10),
                          decoration: BoxDecoration(
                              color: CommonColor.colorMainGreen,
                              borderRadius: BorderRadius.circular(15)),
                          child: Row(
                            children: [
                              Icon(
                                Icons.post_add,
                                size: 14,
                                color: Colors.white,
                              ),
                              Text(
                                "发布",
                                style: TextStyle(
                                    color: Colors.white, fontSize: 13),
                              ),
                            ],
                          ),
                        )
                      ],
                    )
                  ],
                ),
              ),
              onTap: () {
                Get.to(ShiwuAddPage(1))?.then((value) => _getData());
                ;
              },
            ),
            flex: 1,
          ),
          Expanded(
            child: GestureDetector(
              child: Container(
                margin:
                    EdgeInsets.only(top: 12, left: 6, right: 12, bottom: 12),
                padding:
                    EdgeInsets.only(top: 15, left: 10, right: 15, bottom: 15),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(10)),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.list_alt,
                      size: 30,
                      color: CommonColor.colorMainBlue,
                    ),
                    SizedBox(
                      width: 12,
                    ),
                    Column(
                      children: [
                        Text("失物招领"),
                        SizedBox(
                          height: 6,
                        ),
                        Container(
                          padding:
                              EdgeInsets.symmetric(vertical: 4, horizontal: 10),
                          decoration: BoxDecoration(
                              color: CommonColor.colorMainBlue,
                              borderRadius: BorderRadius.circular(15)),
                          child: Row(
                            children: [
                              Icon(
                                Icons.post_add,
                                size: 14,
                                color: Colors.white,
                              ),
                              Text(
                                "发布",
                                style: TextStyle(
                                    color: Colors.white, fontSize: 13),
                              ),
                            ],
                          ),
                        )
                      ],
                    )
                  ],
                ),
              ),
              onTap: () {
                Get.to(ShiwuAddPage(2))?.then((value) => _getData());
              },
            ),
            flex: 1,
          ),
        ],
      );
    } else {
      return _item(index);
    }
  }

  _item(int index) {
    var articleEntity = shiwu[index - 1];
    List<dynamic> imgs = jsonDecode(articleEntity.img ?? '');
    return GestureDetector(
      child: Container(
        margin: EdgeInsets.only(left: 12, right: 12, top: 12),
        padding: EdgeInsets.all(12),
        decoration: BoxDecoration(
            color: articleEntity.ty == 1
                ? CommonColor.colorMainGreenAlpha
                : CommonColor.colorMainBlueAlpha,
            borderRadius: BorderRadius.circular(4)),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Row(
              children: [
                CachedNetworkImage(
                    imageBuilder: (context, image) => CircleAvatar(
                          backgroundImage: image,
                        ),
                    errorWidget: (context, url, error) => CircleAvatar(
                          backgroundImage:
                              AssetImage(UserFeedBackImgs.user_male),
                        ),
                    width: 50,
                    height: 50,
                    imageUrl: (articleEntity?.profile ?? '')),
                SizedBox(
                  width: 12,
                ),
                RichText(
                    text: TextSpan(children: [
                  TextSpan(
                      text: (articleEntity.name ?? "姓名") + "\n",
                      style: TextStyle(
                          color: Color(0XFF333333), fontSize: 13, height: 2)),
                  TextSpan(
                      text: articleEntity?.time ?? "2202-10-11",
                      style: TextStyle(
                          color: Color(0XFF333333), height: 2, fontSize: 13))
                ])),
                Spacer(),
                GestureDetector(
                  child: Container(
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: articleEntity.ty == 1
                            ? CommonColor.colorMainGreen
                            : CommonColor.colorMainBlue,
                        borderRadius: BorderRadius.circular(4)),
                    height: 30,
                    width: 60,
                    child: Text(
                      articleEntity.ty == 1 ? "归还" : "认领",
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                  onTap: () {
                    _showMemberDialog(
                      articleEntity.ty == 1 ? "归还信息" : "验证信息",
                      articleEntity.ty == 1 ? "请输入归还信息" : "请输入验证信息",
                    );
                  },
                ),
              ],
            ),
            Container(
              padding: EdgeInsets.all(6),
              margin: EdgeInsets.only(top: 6),
              decoration: BoxDecoration(
                  color: Color(0X80F1F1F1),
                  borderRadius: BorderRadius.circular(4)),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(articleEntity.title ?? "",
                      style: TextStyle(
                          color: Color(0XFF333333),
                          fontSize: 15,
                          fontWeight: FontWeight.w600)),
                  SizedBox(
                    height: 4,
                  ),
                  Text(articleEntity.content ?? "",
                      style: TextStyle(
                        color: Color(0XFF666666),
                        fontSize: 14,
                      )),
                  SizedBox(
                    height: 4,
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  Visibility(
                    child: GridView.builder(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      gridDelegate:
                          const SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 3,
                        childAspectRatio: 1,
                        crossAxisSpacing: 10,
                      ),
                      itemCount: imgs.length,
                      itemBuilder: (context, index) {
                        //   return Image.file(File(imgAD[index].path));
                        return _singleAD(imgs[index].toString().contains("http")
                            ? imgs[index]
                            : UserFeedBackImgs.url + imgs[index]);
                      },
                    ),
                    visible: imgs.length > 0,
                  ),
                  SizedBox(
                    height: 10,
                  ),
                ],
              ),
            )
          ],
        ),
      ),
      onTap: () {},
    );
  }

  _showMemberDialog(String title, String hint) {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return WillPopScope(
              onWillPop: () async => false,
              child: Scaffold(
                  backgroundColor: Colors.transparent,
                  body: Center(
                    child: SingleChildScrollView(
                      child: Container(
                        margin: EdgeInsets.only(left: 48, right: 48),
                        decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(8)),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            SizedBox(
                              height: 29,
                            ),
                            Text(
                              title,
                              style: TextStyle(
                                  fontSize: 18,
                                  color: CommonColor.color33,
                                  fontWeight: FontWeight.w700),
                            ),
                            SizedBox(
                              height: 25,
                            ),
                            Container(
                              margin: EdgeInsets.only(left: 15, right: 15),
                              padding: EdgeInsets.only(left: 15, right: 15),
                              decoration: BoxDecoration(
                                  color: CommonColor.colorF8,
                                  borderRadius: BorderRadius.circular(4)),
                              child: TextField(
                                maxLines: 1,
                                textAlign: TextAlign.start,
                                enableInteractiveSelection: true,
                                style: TextStyle(
                                  color: CommonColor.color33,
                                  fontSize: 15,
                                  textBaseline: TextBaseline.alphabetic,
                                ),
                                cursorColor: CommonColor.color66,
                                decoration: InputDecoration(
                                  counterText: '',
                                  border: InputBorder.none,
                                  hintText: hint,
                                  hintStyle: TextStyle(
                                      fontSize: 15, color: CommonColor.colorCF),
                                ),
                              ),
                            ),
                            SizedBox(
                              height: 25,
                            ),
                            Divider(
                              height: 1,
                              color: CommonColor.colorEE,
                            ),
                            Container(
                              height: 50,
                              child: Flex(
                                direction: Axis.horizontal,
                                children: <Widget>[
                                  Expanded(
                                    flex: 1,
                                    child: GestureDetector(
                                      onTap: () {
                                        Get.back();
                                      },
                                      child: Text(
                                        "取消",
                                        textAlign: TextAlign.center,
                                        style: TextStyle(
                                            fontSize: 18,
                                            color: CommonColor.color99),
                                      ),
                                    ),
                                  ),
                                  VerticalDivider(
                                    width: 1,
                                    color: CommonColor.colorEE,
                                  ),
                                  Expanded(
                                    flex: 1,
                                    child: GestureDetector(
                                      onTap: () {
                                        QmToast.toast("已发送验证信息,请耐心等待");
                                        Get.back();
                                      },
                                      child: Text(
                                        "验证",
                                        textAlign: TextAlign.center,
                                        style: TextStyle(
                                          fontSize: 18,
                                          color: CommonColor.colorMainGreen,
                                        ),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  )));
        });
  }

  _singleAD(String pos) {
    return InstaImageViewer(
      child: CachedNetworkImage(
        width: 68,
        height: 68,
        fit: BoxFit.cover,
        alignment: Alignment.topCenter,
        imageUrl: pos,
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _getData();
  }

  _getData() {
    try {
      List<dynamic> data = jsonDecode(Moni.getShiwu());
      List<ShiwuEntity> gs = [];
      if (data != null) {
        data.forEach((element) {
          gs.add(ShiwuEntity.fromJson(element));
        });
      }
      setState(() {
        shiwu.clear();
        shiwu.addAll(gs);
      });
      shiwu.sort((a, b) {
        return (b?.time ?? '').compareTo(a?.time ?? "");
      });
    } catch (e) {
      print(e);
    }
  }

  Future<void> myAsyncRefreshFunction() async {
    _getData();
  }
}
